#!/bin/bash
# ----------------------------------------------------------------------
# neds handy rotating-filesystem-snapshot utility: daily snapshots
# ----------------------------------------------------------------------
# intended to be run daily as a cron job
# ----------------------------------------------------------------------

unset PATH

# ------------- system commands used by this script --------------------
ID=/usr/bin/id;
ECHO=/bin/echo;

MOUNT=/bin/mount;
RM=/bin/rm;
MV=/bin/mv;
CP=/bin/cp;

RSYNC=/usr/bin/rsync;

SSH=/usr/bin/ssh;
# ------------- file locations -----------------------------------------

SNAPSHOT_RW=/data/veni_backups;  # this is the directory on the other server

BACKUP_DIR=/var/www/twiki;  # this is the directory we're backing up

BACKUP=msl;  # this is the other server


# ------------- the script itself --------------------------------------

# make sure we're running as root
if (( `$ID -u` != 0 )); then { $ECHO "Sorry, must be root.  Exiting..."; exit; } fi

# attempt to chmod the directory to RW 
$SSH $BACKUP chmod 600 $SNAPSHOT_RW ;
if (( $? )); then
{
	$ECHO "snapshot: could not chmod $SNAPSHOT_RW readwrite";
	exit;
}
fi;


# step 1: delete the oldest snapshot, if it exists:
$SSH $BACKUP "if [ -d $SNAPSHOT_RW/daily.6 ] ; then			\
$RM -rf $SNAPSHOT_RW/daily.6 ;				\
fi ;"

# step 2: shift the middle snapshots(s) back by one, if they exist
$SSH $BACKUP "if [ -d $SNAPSHOT_RW/daily.5 ] ; then			\
$MV $SNAPSHOT_RW/daily.5 $SNAPSHOT_RW/daily.6 ;	\
fi;"
$SSH $BACKUP "if [ -d $SNAPSHOT_RW/daily.4 ] ; then			\
$MV $SNAPSHOT_RW/daily.4 $SNAPSHOT_RW/daily.5 ;	\
fi;"
$SSH $BACKUP "if [ -d $SNAPSHOT_RW/daily.3 ] ; then			\
$MV $SNAPSHOT_RW/daily.3 $SNAPSHOT_RW/daily.4 ;	\
fi;"
$SSH $BACKUP "if [ -d $SNAPSHOT_RW/daily.2 ] ; then			\
$MV $SNAPSHOT_RW/daily.2 $SNAPSHOT_RW/daily.3 ;	\
fi;"
$SSH $BACKUP "if [ -d $SNAPSHOT_RW/daily.1 ] ; then			\
$MV $SNAPSHOT_RW/daily.1 $SNAPSHOT_RW/daily.2 ;	\
fi;"
$SSH $BACKUP "if [ -d $SNAPSHOT_RW/daily.0 ] ; then			\
$MV $SNAPSHOT_RW/daily.0 $SNAPSHOT_RW/daily.1 ;	\
fi;"

# step 3: make a hard-link-only (except for dirs) copy of
# daily.1, assuming that exists, into daily.0
$RSYNC -va --delete --link-dest=../daily.1 $BACKUP_DIR root@msl:/data/veni_backups/daily.0;

# now chmod the directory to readonly

$SSH $BACKUP chmod 400 $SNAPSHOT_RW ;
if (( $? )); then
{
	$ECHO "snapshot: could not chmod $SNAPSHOT_RW readonly";
	exit;
} fi;
